package com.swordxu.yim.android.ui.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.swordxu.yim.R;
import com.swordxu.yim.android.app.IMEntrance;
import com.swordxu.yim.android.cache.biz.CacheHub;
import com.swordxu.yim.android.config.SysConstant;
import com.swordxu.yim.android.conn.NetStateDispach;
import com.swordxu.yim.android.imlib.IMActions;
import com.swordxu.yim.android.imlib.IMLoginManager;
import com.swordxu.yim.android.imlib.common.ErrorCode;
import com.swordxu.yim.android.imlib.db.IMDbManager;
import com.swordxu.yim.android.imlib.service.IMService;
import com.swordxu.yim.android.log.Logger;
import com.swordxu.yim.android.ui.base.YimBaseActivity;
import com.swordxu.yim.android.ui.utils.IMServiceHelper;

import java.util.ArrayList;
import java.util.List;

public class LoginActivity extends YimBaseActivity implements IMServiceHelper.OnIMServiceListner {
    EditText etAccount;     //账号输入框
    EditText etPwd;         //密码输入框
    Button btLogin;         //登录按钮

    private View loginPage;
    private View splashPage;
    private View mLoginStatusView;

    private Handler uiHandler = new Handler();
    private IMLoginManager imLoginMgr;
    private Logger logger = Logger.getLogger(LoginActivity.class);
    private IMServiceHelper imServiceHelper = new IMServiceHelper();
    private IMDbManager.LoginIdentity loginIdentity;
    private boolean autoLogin = false;
    private InputMethodManager intputManager;
    public static Context instance = null;

    private String getLoginErrorTip(int errorCode, int msgServerErrorCode) {
        switch (errorCode) {
            case ErrorCode.E_CONNECT_LOGIN_SERVER_FAILED :
                return getString(R.string.connect_login_server_failed);
            case ErrorCode.E_REQ_MSG_SERVER_ADDRS_FAILED :
                return getString(R.string.req_msg_server_addrs_failed);
            case ErrorCode.E_CONNECT_MSG_SERVER_FAILED :
                return getString(R.string.connect_msg_server_failed);
            case ErrorCode.E_LOGIN_MSG_SERVER_FAILED :
                return getString(R.string.login_msg_server_failed);
            case ErrorCode.E_LOGIN_GENERAL_FAILED :
                return getString(R.string.login_error_general_failed);
            case ErrorCode.E_REQ_LOGIN_SERVER_ADDRS_FAILED :
                return getString(R.string.login_error_fetch_login_server_addrs_failed);
            case ErrorCode.E_MSG_SERVER_ERROR_CODE :
                return String.format("%s %s:%d", getString(R.string.login_msg_server_failed), getString(R.string.error_code_name), msgServerErrorCode);
            default :
                return getString(R.string.login_error_unexpected);

        }
    }

    private void onLoginError(int errorCode, int msgServerErrorCode) {
        logger.e("login#onLoginError -> errorCode:%d, msgServerErrorCode:%d", errorCode, msgServerErrorCode);

        showLoginPage();

        String errorTip = getLoginErrorTip(errorCode, msgServerErrorCode);
        logger.d("login#errorTip:%s", errorTip);

        mLoginStatusView.setVisibility(View.GONE);

        Toast.makeText(this, errorTip, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onAction(String action, Intent intent, BroadcastReceiver broadcastReceiver) {
        logger.d("login#onAction -> action:%s", action);
        System.out.println("login#onAction -> action:%s" + action);
        if (action.equals(IMActions.ACTION_LOGIN_RESULT)) {
            int errorCode = intent.getIntExtra(SysConstant.lOGIN_ERROR_CODE_KEY, -1);
            int msgServerErrorCode = intent.getIntExtra(SysConstant.KEY_MSG_SERVER_ERROR_CODE, 0);

            if (errorCode != ErrorCode.S_OK) {
                onLoginError(errorCode, msgServerErrorCode);
            } else {
                System.out.println("登录msgserver成功");
                onLoginSuccess();
            }
        }
    }

    private void onLoginSuccess() {
        logger.i("login#onLoginSuccess");
        CacheHub.getInstance().setLoginUser(imServiceHelper.getIMService().getLoginManager().getLoginUser());
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(intent);
        LoginActivity.this.finish();
    }

    @Override
    protected void onStop() {
        NetStateDispach.getInstance().unregister(LoginActivity.class);
        super.onStop();
    }

    @Override
    public void onIMServiceConnected() {
        // TODO Auto-generated method stub

        logger.d("login#onIMServiceConnected");
        IMService imService = imServiceHelper.getIMService();
        if (imService == null) {
            return;
        }

        imLoginMgr = imService.getLoginManager();

        if (imLoginMgr != null) {
            logger.i("chat#connect im service ok");
        }

        try {
            loginIdentity = imService.getDbManager().loadLoginIdentity();
            if (loginIdentity == null) {
                handleNoLoginIdentity();
            } else {
                handleGotLoginIdentity();
            }
        } catch (Exception e) {
            logger.w("loadIdentity failed");
        }
    }

    /**
     * 本地没有登录数据
     */
    private void handleNoLoginIdentity() {
        logger.i("login#handleNoLoginIdentity");

        if (autoLogin) {
            //no login identity yet, show login page a few seconds delay
            uiHandler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    showLoginPage();
                }
            }, 1500);
        }
    }

    /**
     * 使用本地登录数据
     */
    private void handleGotLoginIdentity() {
        logger.i("login#handleGotLoginIdentity");

        logger.d("login#loginId:%s", loginIdentity.loginId);

        etAccount.setText(loginIdentity.loginId);
        etPwd.setText(loginIdentity.pwd);

        if (autoLogin) {
            uiHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    logger.d("login#start auto login");

                    if (imLoginMgr != null) {
                        imLoginMgr.login(loginIdentity.loginId, loginIdentity.pwd, false, false);
                    }
                }
            }, 1500);
        }
    }

    /**
     * 显示登录界面
     */
    private void showLoginPage() {
        splashPage.setVisibility(View.GONE);
        loginPage.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        intputManager = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE);
        logger.d("login#onCreate");
        List<String> actions = new ArrayList<String>();
        actions.add(IMActions.ACTION_LOGIN_RESULT);
        if (!imServiceHelper.connect(getApplicationContext(), actions, IMServiceHelper.INTENT_NO_PRIORITY, this)) {
            logger.e("login#fatal,  connect im service failed");
        }
        IMEntrance.getInstance().setContext(LoginActivity.this);
        initHandler();
        setContentView(R.layout.activity_login);
        instance = this;
        initView();
    }

    /**
     * 初始化handler
     */
    @Override
    protected void initHandler() {

    }

    /**
     * 初始化UI组件
     */
    public void initView() {
        etAccount = (EditText)findViewById(R.id.et_account);
        etPwd = (EditText)findViewById(R.id.et_pwd);
        btLogin = (Button)findViewById(R.id.bt_login);

        splashPage = findViewById(R.id.splash_page);
        loginPage = findViewById(R.id.login_page);
        mLoginStatusView = findViewById(R.id.login_status);

        btLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intputManager.hideSoftInputFromWindow(etPwd.getWindowToken(), 0);
                login(v);
            }
        });

        uiHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                showLoginPage();
            }
        }, 1500);
    }

    /**
     * 登录
     * @param view
     */
    public void login(View view) {
        String account = etAccount.getText().toString();
        String pwd = etPwd.getText().toString();
        boolean isCancel = false;
        View focusView = null;
        //校验登录输入
        if (TextUtils.isEmpty(account)) {
            Toast.makeText(this, "请输入账号", Toast.LENGTH_LONG).show();
            isCancel = true;
        }
        if (TextUtils.isEmpty(pwd)) {
            Toast.makeText(this, "请输入密码", Toast.LENGTH_LONG).show();
            isCancel = true;
        } else if(pwd.length() < 6) {
            Toast.makeText(this, "请输入至少6位密码", Toast.LENGTH_LONG).show();
            isCancel = true;
        }
        if (isCancel) {
            return;
        }
        Log.d("", "卧槽");
        Toast.makeText(this, "登录", Toast.LENGTH_LONG).show();
        showProgress(true);
        if (imLoginMgr != null) {
            imLoginMgr.login(account, pwd, true, true);
        }
    }

    private void showProgress(final boolean show) {
        if (show) {
            mLoginStatusView.setVisibility(View.VISIBLE);
        } else {
            mLoginStatusView.setVisibility(View.GONE);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.login, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
